from utils import file, common
from lib.config.index import server_config


class NetFileSystem:
    def __init__(self):
        self.__root = server_config.get_root()
        self.__projects = server_config.get_projects()
        # print(server_config.get_projects())
        self.__current_project = server_config.get_default_project()
        self.__max_file_size = 8 * 1024

    def get_max_file_size(self):
        return self.__max_file_size

    def get_root(self):
        return self.__root

    def set_root(self, path):
        self.__root = path

    def set_current_project(self, name):
        """切换项目"""
        if name == "default":
            self.__current_project = server_config.get_default_project()
        for pro in self.__projects:
            if pro["name"] == name:
                self.__current_project = pro

    def get_current_project(self):
        return self.__current_project

    def read(self, net_path):
        real_path = self.real_path(net_path)
        return self.read_file(real_path)

    def read_file(self, real_path):
        info = file.get_file_info(real_path)
        size = info["size"]
        # print(info)
        if size > 0 and size < self.get_max_file_size():
            return (info, self.safe_read(real_path))
        elif size > 0:
            return (info, bytearray([]))

        return (info, None)

    async def write_chunk(self, stream, net_path):
        real_path = self.real_path(net_path)
        f = open(real_path, "rb")
        # print(stream, net_path)
        common.collect_gc()
        try:
            while True:
                data = f.read(1024 * 4)
                if not data:
                    break
                stream.write(data)
                await stream.drain()
            f.close()
            stream.close()
        except Exception as e:
            # print(e)
            f.close()
            stream.close()

    def safe_read(self, real_path):
        file = open(real_path, "rb")
        data = file.read()
        file.close()
        return data

    def real_path(self, net_path):
        if self.__current_project:
            project_path = self.__current_project["path"]
            return f"{self.__root}{project_path}{net_path}"
        return f"{self.__root}{net_path}"


net_fs = NetFileSystem()
